package com.csdj.web;

import com.csdj.entity.Employee;
import com.csdj.service.EmployeeService;
import com.csdj.service.impl.EmployeeServiceImpl;
import com.csdj.util.MyConfig;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@WebServlet("/uploadEmp")
@MultipartConfig //文件上传时需要添加此注解
public class UploadEmpServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置响应编码
        resp.setCharacterEncoding("utf-8");
        //获取请求参数
        String name = req.getParameter("name");
        String pwd = req.getParameter("pwd");
        String depteid = req.getParameter("depteid");
        String img = "";
        String email = req.getParameter("email");

        //获取文件请求对象
        Part part = req.getPart("img");
        System.out.println("文件名:" + part.getName());
        System.out.println("文件大小:" + part.getSize());
        System.out.println("文件类型:" + part.getContentType());
        System.out.println("文件属性:" + part.getSubmittedFileName());
        //限制文件上传大小
        //限制
        long size = part.getSize();
        if (size > 0 && size < 5 * 1024 * 1024) {
            String contentType = part.getContentType();
            if (contentType.startsWith("image")) {
                String fileName = part.getSubmittedFileName();
                //获取文件后缀
                String fileSuffix = fileName.substring(fileName.lastIndexOf("."));
                //新文件名  自行定义
                String newFileName = UUID.randomUUID() + fileSuffix;
                System.out.println("1111111111111111111111111111111111111");
                //创建文件对象
                String filePath = MyConfig.getValue("filePath");
                System.out.println("filePath:" + filePath);
                try {
                    part.write(filePath + File.separatorChar + newFileName);
                    img = newFileName;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                System.out.println("part:上传的不是图片格式");
            }
        } else {
            System.out.println("part:不符合大小");
        }

        Employee emp = new Employee();
        emp.setName(name);
        emp.setPassword(pwd);
        emp.setDepartmentId(Integer.parseInt(depteid));
        emp.setImg(img);
        emp.setEmail(email);
        EmployeeService employeeService = new EmployeeServiceImpl();
        int i = employeeService.addEmp(emp);
        if (i > 0) {
            resp.sendRedirect("login.jsp");
        } else {
            resp.sendRedirect("addEmp.jsp");
        }
    }
}
